<?php

namespace app\common;

use think\App;
use think\Log;

class CanMingLog extends Log
{
    public function record($msg, $type = 'info', array $context = [])
    {
        if (!$this->allowWrite) {
            return;
        }

        if (is_string($msg) && !empty($context)) {
            $replace = [];
            foreach ($context as $key => $val) {
                $replace['{' . $key . '}'] = $val;
            }

            $msg = strtr($msg, $replace);
        }

        if ($type == 'error' || $type == 'warning') {
            $msg .= PHP_EOL;
            $trace = debug_backtrace();
            foreach ($trace as $item) {
                if (isset($item['file']) && isset($item['line'])) {
                    $msg .= '# ' . $item['file'] . ':' . $item['line'] . PHP_EOL;
                }
            }

            $server = $_SERVER;
            $msg .= "[ message ]" . PHP_EOL;

            foreach ($server as $key => $value) {
                if (is_array($value)) {
                    $value = json_encode($value, true);
                }
                $msg .= '- ' . $key . ':' . $value . PHP_EOL;
            }

            $msg .= "[ GET ]" . PHP_EOL;
            $msg .= var_export(App::getInstance()->request->get(), true) . PHP_EOL;

            $msg .= "[ POST ]" . PHP_EOL;
            $msg .= var_export(App::getInstance()->request->post(), true) . PHP_EOL;
        }


        if (PHP_SAPI == 'cli') {
            // 命令行日志实时写入
            $this->write($msg, $type, true);
        } else {
            $this->log[$type][] = $msg;
        }

        if ($type == 'error') {
            \Sentry\captureMessage($msg);
        }

        return $this;
    }
}
